package cn.jasonone.jame.model;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import lombok.Getter;
import lombok.Setter;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 列表控件
 * @param <T> 列表项类型
 * @author Jason
 * @since 1.0.0
 */
public class GList<T extends Spirit> extends Spirit {
    private ObservableList<T> spirits = FXCollections.observableArrayList();
    @Getter
    private T selected;
    @Getter
    private int selectedIndex=-1;
    @Setter
    @Getter
    private int padding=5;

    /**
     * 创建一个列表
     * @param ts 列表项
     */
    public GList(T ... ts){
        this.add(ts);
    }

    public void clear(){
        this.spirits.clear();
        this.selected=null;
        this.selectedIndex=-1;
    }

    public void setSelected(T selected) {
        if (spirits.contains(selected)) {
            selectedIndex = spirits.indexOf(selected);
        }
    }

    public void setSelectedIndex(int index) {
        if (spirits.size() > index) {
            this.selected = this.spirits.get(index);
            this.selectedIndex = index;
        }
    }

    /**
     * 添加列表项
     * @param ts 列表项列表
     */
    public void add(T...ts) {
        spirits.addAll(ts);
    }

    public void remove(T t) {
        spirits.remove(t);
    }

    public void remove(int index) {
        spirits.remove(index);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        int i = 0;
        Iterator<T> iterator = spirits.iterator();
        while (iterator.hasNext()) {
            T t = iterator.next();
            if (t.isContains(e.getX(), e.getY())) {
                this.selected = t;
                selectedIndex = i;
            }
            i++;
        }
    }


    @Override
    public void draw(GraphicsContext gc) {
        super.draw(gc);
        Iterator<T> iterator = spirits.iterator();
        int i = 0;
        double height = 0;
        while (iterator.hasNext()) {
            T t = iterator.next();
            t.moveTo(getX(), getY() + height + padding);
            if(t.getFont() == null){
                t.setFont(getFont());
            }
            t.draw(gc);
            height += t.getHeight()+padding;
            i++;
        }
    }

    @Override
    public double getHeight() {
        Iterator<T> iterator = spirits.iterator();
        double height = 0;
        while (iterator.hasNext()) {
            height += iterator.next().getHeight()+padding;
        }
        return height;
    }
}
